/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.app.server.listener;

import com.bugull.farm.app.server.cache.AppCache;
import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.cache.ProtocolCache;
import com.bugull.farm.core.frame.structure.Param;
import com.bugull.farm.core.utils.ByteUtil;
import com.bugull.redis.listener.TopicListener;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;

import java.util.Arrays;
import java.util.Set;

import org.apache.logging.log4j.*;


/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class AppTopicListener extends TopicListener {
    
    private final static Logger logger = LogManager.getLogger(AppTopicListener.class);
    private final byte[] DEFAULT_MAC= new byte[]{(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF};
    
    @Override
    public void onTopicMessage(String topic, byte[] msg) {
    	PropertiesCache props = PropertiesCache.getInstance();
    	ProtocolCache cache = ProtocolCache.getInstance();
        if(!topic.equals(props.get("redis.topic.app"))){
            return;
        }
        if(msg.length < props.getInt("frame.min.size")){
            return;
        }
        try {
	        String mac = ByteUtil.toHexString(Arrays.copyOfRange(msg, 2, 8));  //start at position 2, length 6
	        int cmdIndex = cache.getIndex("cmd");
	        String cmd = ByteUtil.toHexString(msg[cmdIndex]);
	        int serIndex = cache.getIndex("serial");
	        Param serParam = cache.getParam(cmd, "serial", false);
	        String serial = ByteUtil.toHexString(Arrays.copyOfRange(msg, serIndex, serIndex + serParam.getLen()));
	        processResponse(mac, cmd, serial, msg);
        } catch (Exception e) {
        	e.printStackTrace();
        	logger.error(e);
        }
//        if(cmd == props.getByte("")){
        	//TODO
//        	byte slen = msg[17];
//        	byte[] param = Arrays.copyOfRange(msg, 18, 18+slen);
//        	processEvent(DEFAULT_MAC, cmd, param, msg);
//        }else if(cmd==FarmConstant.EVENT_UPLOAD ||
//        		cmd==FarmConstant.EVENT_ONLINE ){
//            byte[] param = new byte[1];
//            param[0] = FarmConstant.VAL_00;
//            processEvent(mac, cmd, param, msg);
//        }else{
//        	//response
//            byte[] seq = Arrays.copyOfRange(msg, 10, 12);  //sequence number
//            processResponse(mac, seq, cmd, msg);
//        }
    }
    
    private void processResponse(String mac, String seq, String cmd, byte[] data){
        AppCache cache = AppCache.getInstance();
        ChannelGroup group = cache.getRequestGroup(mac + seq + cmd);
        if(group != null){
            ByteBuf buf = Unpooled.buffer();
            buf.writeBytes(data);
            group.writeAndFlush(buf);
        }
        cache.removeRequestGroup(mac + seq + cmd, group);
    }
    
    private void processEvent(String mac, String cmd, String param, byte[] data){
        AppCache cache = AppCache.getInstance();
        ChannelGroup group = cache.getSubscribeGroup(mac + cmd + param);
        if(group != null){
            ByteBuf buf = Unpooled.buffer();
            buf.writeBytes(data);
            group.writeAndFlush(buf);
        }
    }

}
